package com.bdrm.service.impl;

import com.bdrm.constant.MessageConstant;
import com.bdrm.context.BaseContext;
import com.bdrm.dto.OrderPageQueryDTO;
import com.bdrm.dto.OrderRejectionDTO;
import com.bdrm.dto.OrdersCancelDTO;
import com.bdrm.dto.OrdersSubmitDTO;
import com.bdrm.entity.AddressBook;
import com.bdrm.entity.OrderDetail;
import com.bdrm.entity.Orders;
import com.bdrm.entity.ShoppingCart;
import com.bdrm.exception.AddressBookBusinessException;
import com.bdrm.exception.OrderBusinessException;
import com.bdrm.mapper.AddressBookMapper;
import com.bdrm.mapper.OrderDetailMapper;
import com.bdrm.mapper.OrderMapper;
import com.bdrm.mapper.ShoppingCartMapper;
import com.bdrm.result.PageResult;
import com.bdrm.service.OrderService;
import com.bdrm.vo.OrderInfoVO;
import com.bdrm.vo.OrderStatisticsVO;
import com.bdrm.vo.OrderSubmitVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    /**
     *  用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 地址为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            //抛出错误
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 购物车为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size() == 0){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(addressBook.getDetail());
        orderMapper.insert(orders);

        // 向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);

        // 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 封装VO返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    @Override
    public void update(String orderNumber) {
        // 根据订单号查询订单信息
        Orders ordersDB = orderMapper.getByNumber(orderNumber);
        Long userId = BaseContext.getCurrentId();
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .userId(userId)
                .build();
        orderMapper.update(orders);
    }

    // 查询订单详情
    @Override
    public OrderInfoVO detail(Long id) {

        // 根据订单id查询订单数据
        Orders orders = orderMapper.getById(id);

//        if (orders != null){
            List<OrderDetail>orderDetails = orderDetailMapper.getByOrderId(orders.getId());
            OrderInfoVO orderInfoVO = new OrderInfoVO();

            BeanUtils.copyProperties(orders, orderInfoVO);
            orderInfoVO.setOrderDetailList(orderDetails);
//        }
        return orderInfoVO;
    }

    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();

        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetails.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    public PageResult pageQuery(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        OrderPageQueryDTO orderPageQueryDTO = new OrderPageQueryDTO();
        Long userId = BaseContext.getCurrentId();
        orderPageQueryDTO.setUserId(userId);
        orderPageQueryDTO.setStatus(status);

        Page<Orders> pageQuery = orderDetailMapper.pageQuery(orderPageQueryDTO);

        ArrayList<OrderInfoVO> list = new ArrayList<>();
        // 将查询到数据封装到OrderInfoVO中
        if (pageQuery !=null && pageQuery.getTotal() >0){
            for (Orders orders : pageQuery) {
                Long orderId = orders.getId();

                // 根据订单id查询用户详情
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                BeanUtils.copyProperties(orders,orderInfoVO);
                orderInfoVO.setOrderDetailList(orderDetailList);
                list.add(orderInfoVO);
            }
        }
        return new PageResult(pageQuery.getTotal(),list);
    }

    @Override
    public PageResult conditionSearch(OrderPageQueryDTO orderPageQueryDTO) {
        PageHelper.startPage(orderPageQueryDTO.getPage(),orderPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(orderPageQueryDTO);

        List<OrderInfoVO> orderInfoVO = getOrderDetailInfoVO(orders);
        return new PageResult(orders.getTotal(),orderInfoVO);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据各状态统计
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);

        // 返回到封装的VO里面
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);

        return orderStatisticsVO;
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // TODO 由于个人用户不能是微信支付，则不实现退款功能

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setRejectionReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeById(Long id) {
        // 根据id查询订单
        Orders order = orderMapper.getById(id);

        // 校验一下订单是否存在状态是否为以已接单
        if (order ==null && !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 拒单
     */

    @Override
    public void rejection(OrderRejectionDTO orderRejectionDTO) {
        //根据id查询订单
        Orders order = orderMapper.getById(orderRejectionDTO.getId());

        //判断是否为待接单状态
        if (!order.getStatus().equals(Orders.TO_BE_CONFIRMED) && order !=null){
             throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(orderRejectionDTO.getId());
        orders.setRejectionReason(orderRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 接单
     * @param id
     */
    @Override
    public void confirm(Long id) {
        Orders order = orderMapper.getById(id);
        if (!order.getStatus().equals(Orders.TO_BE_CONFIRMED) && order != null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderInfoVO detailById(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());

        OrderInfoVO orderInfoVO = new OrderInfoVO();
        BeanUtils.copyProperties(order,orderInfoVO);
        orderInfoVO.setOrderDetailList(orderDetailList);
        return orderInfoVO;
    }

    /**
     * 派送
     * @param id
     */
    @Override
    public void deliveryById(Long id) {
        Orders order = orderMapper.getById(id);
        if (order !=null && !order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    private List<OrderInfoVO> getOrderDetailInfoVO(Page<Orders> orders) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderInfoVO> list = new ArrayList<>();

        List<Orders> result = orders.getResult();
        for (Orders order : result){
            OrderInfoVO orderInfoVO = new OrderInfoVO();
            BeanUtils.copyProperties(order,orderInfoVO);
            String orderDishesStr = getOrderDishesStr(order);

            // 将订单菜品信息封装到orderVO中，并添加到orderVOList
            orderInfoVO.setOrderDishes(orderDishesStr);
            list.add(orderInfoVO);
        }
        return list;
    }

    /**
     *  根据订单id获取菜品信息字符串
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders){
        // 根据订单id查询菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串 如：珍珠奶茶*3
        List<String> o = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ';';
            return orderDish;
        }).collect(Collectors.toList());


        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("",o);
    }
}
